<template>
    <view class="file-upload-list">
        <u-upload @afterRead="afterRead" @delete="deletePic" v-model="fileData" :max-count="max" :auto-upload="true"
            :file-list="fileList"></u-upload>
    </view>
</template>
<script>
import { uploadFile } from "@/api/system/user"
export default {
    name: 'FileUpload',
    props: {
        value: { type: Object, default: [] },
        max: { type: Number, default: 3 }
    },
    data() {
        return {
            fileList: [],
            fileData: []
        }
    },
    computed: {
    },
    watch: {
        // fileList(newVal) {
        //     console.log(newVal);
        //     const url = newVal.map(ele => ele.url).join(',')
        //     this.$emit('input', url)
        // }
    },
    methods: {
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        async afterRead(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                uploadFile({ filePath: lists[i].url }).then(result => {
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result.data
                    }))
                    fileListLen++
                    const url = this.fileList.map(ele => ele.url).join(',')
                    this.$emit('input', url)
                }).catch(() => {
                    uni.showToast({
                        title: '上传失败，请重新上传！', duration: 2000, icon: 'none'
                    });
                    setTimeout(() => {
                        this[`fileList${event.name}`].splice(event.index, 1)
                    }, 1000);
                })
            }
        },
    }
}
</script>
<style lang="scss">
.file-upload-list {
    padding-top: 16rpx;

    image {
        width: 160rpx;
        height: 160rpx;
    }
}
</style>
